package com.platform.controller;

import com.platform.entity.*;
import com.platform.entity.excel.CashOutExcel;
import com.platform.entity.excel.OrderExcel;
import com.platform.service.*;
import com.platform.util.CashStatusEnum;
import com.platform.util.OrderStatusEnum;
import com.platform.utils.PageUtils;
import com.platform.utils.Query;
import com.platform.utils.R;
import com.platform.utils.excel.ExcelExport;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 提现申请表Controller
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2019-02-17 10:44:13
 */
@RestController
@RequestMapping("cashout")
public class CashOutController extends AbstractController {
    @Autowired
    private CashOutService cashOutService;
    @Autowired
    private UserAssetService userAssetService;
    @Autowired
    private MerchantInfomationService merchantInfomationService;
    @Autowired
    private MerchantService merchantService;


    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("cashout:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<CashOutEntity> tCashOutList = cashOutService.queryList(query);
        int total = cashOutService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(tCashOutList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("cashout:info")
    public R info(@PathVariable("id") Long id) {
        CashOutEntity tCashOut = cashOutService.queryObject(id);

        return R.ok().put("cashout", tCashOut);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("cashout:save")
    public R save(@RequestBody CashOutEntity tCashOut) {
        cashOutService.save(tCashOut);

        return R.ok();
    }

    /**
     * 修改 审核通过
     */
    @RequestMapping("/update")
    @RequiresPermissions("cashout:update")
    public R update(@RequestBody CashOutEntity tCashOut) {
        SysUserEntity user = getUser();
        CashOutEntity cash = cashOutService.queryObject(tCashOut.getId());
        cash.setStatus(tCashOut.getStatus());
        cash.setVersion(tCashOut.getVersion());
        cash.setUpdateDate(new Date());
        cash.setUpdateUser(user.getUsername());
        int i = cashOutService.update(cash);
        if (i > 0) {
            return R.ok();
        }
        return R.error("审核失败,请查看用户资金");
    }

    /**
     * 修改
     */
    @RequestMapping("/finish")
    @RequiresPermissions("cashout:update")
    public R finish(@RequestBody CashOutEntity tCashOut) {
        SysUserEntity user = getUser();
        CashOutEntity cash = cashOutService.queryObject(tCashOut.getId());
        cash.setFinishDate(new Date());
        cash.setFinishUser(user.getUsername());
        cash.setStatus(tCashOut.getStatus());
        cash.setVersion(tCashOut.getVersion());
        cash.setRealAmount(tCashOut.getAmount());
        int result = cashOutService.finish(cash);
        if (result > 0) {
            return R.ok();
        }
        return R.error("请查看用户资金");
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("cashout:delete")
    public R delete(@RequestBody Long[] ids) {
        cashOutService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<CashOutEntity> list = cashOutService.queryList(params);

        return R.ok().put("list", list);
    }
    @RequestMapping("/export")
    @RequiresPermissions("cashout:export")
    public void code(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "cardNo", required = false) String cardNo,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "index", required = false) Integer index,
            @RequestParam(value = "size", required = false) Integer size, HttpServletResponse response) throws IOException {

        List<CashOutExcel> cashList = cashOutService.queryListExcel(name, phone, cardNo, status, index, size);
        String fileName= CashStatusEnum.getDesc(status);
        String sheetName=CashStatusEnum.getDesc(status);
        ExcelExport ee = new ExcelExport(fileName);
        String[] header = new String[]{"订单号", "手机号", "身份证号", "真实姓名", "卡银行", "开户行","银行卡号", "预留手机",
                "状态","申请金额","实际到账", "修改时间", "修改人", "完成时间", "完成人", "创建时间"};
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (CashOutExcel outExcel : cashList) {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            map.put("cashNo", outExcel.getCashNo());
            map.put("phone", outExcel.getPhone());
            map.put("idCardNo", outExcel.getIdCardNo());
            map.put("realName", outExcel.getRealName());
            map.put("cardBank", outExcel.getCardBank());
            map.put("openBank", outExcel.getOpenBank());
            map.put("cardNo", outExcel.getCardNo());
            map.put("reservePhone", outExcel.getReservePhone());
            map.put("status", CashStatusEnum.getDesc(outExcel.getStatus()));
            map.put("amount", outExcel.getAmount());
            map.put("realAmount", outExcel.getRealAmount());
            map.put("updateDate", outExcel.getUpdateDate());
            map.put("updateUser", outExcel.getUpdateUser() );
            map.put("finishDate", outExcel.getFinishDate());
            map.put("finishUser", outExcel.getFinishUser());
            map.put("createDate", outExcel.getCreateDate());
            list.add(map);
        }
        ee.addSheetByMap(sheetName, list, header);
        ee.export(response);
    }

    /**
     * 申请通过
     * @param cashOutEntity
     * @return
     */
    @RequestMapping("/pass")
    public R pass(@RequestBody CashOutEntity cashOutEntity){
        CashOutEntity coe = cashOutService.queryObject(cashOutEntity.getId());
//        UserAssetEntity assetEntity = userAssetService.queryObjectForUid(coe.getUid());
//        if(assetEntity==null){
//            return R.error();
//        }
        MerchantEntity merchantEntity = merchantService.queryObjectByUid(coe.getUid().intValue());
        MerchantInfomationEntity merchantInfomationEntity = merchantInfomationService.queryObjectByMid(merchantEntity.getId());
        try {
            if(cashOutService.success(cashOutEntity.getId().intValue(),cashOutEntity.getStatus(),cashOutEntity.getVersion(),merchantInfomationEntity)==false){
                return R.error();
            }
            return R.ok();
        }catch (Exception e){
            return R.error();
        }
    }

    /**
     * 审核失败
     * @param cashOutEntity
     * @return
     */
    @RequestMapping("/fail")
    public R fail(@RequestBody CashOutEntity cashOutEntity){
        try {
            CashOutEntity cashOut = cashOutService.queryObject(cashOutEntity.getId());
            cashOut.setStatus(3);
            cashOut.setVersion(cashOutEntity.getVersion());
            cashOut.setId(cashOutEntity.getId());

            MerchantEntity merchantEntity = merchantService.queryObjectByUid(cashOut.getUid().intValue());
            MerchantInfomationEntity merchantInfomationEntity = merchantInfomationService.queryObjectByMid(merchantEntity.getId());
            if(cashOutService.cashOutFail(cashOut,merchantInfomationEntity)==false){
                return R.error();
            }
            return R.ok();
        }catch (Exception e){
            return R.error();
        }

    }

    /**
     * 提现完成
     * @param cashOutEntity
     * @return
     */
    @RequestMapping("/success")
    public R success(@RequestBody CashOutEntity cashOutEntity){
        if(cashOutService.updateCashOutStatus(cashOutEntity.getStatus(),cashOutEntity.getId().intValue(),cashOutEntity.getVersion())<=0){
            return R.error();
        }
        return R.ok();
    }


}
